﻿using DataStandard.ProtocoType;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace DataStandard
{
    /// <summary>
    /// 协议项
    /// </summary>
    public class ProtocolItem : IDisposable
    {
        #region 属性

        public string Name { get; set; }

        public InterfaceProtocoType InterfaceType { get; set; } = null;

        public List<DataItem> dataItems { get; set; }
        #endregion

        #region 线程管理
        /// <summary>
        /// 线程计时器
        /// 在其他地方赋值
        /// </summary>
        private long millisecond_Thread = 0;
        /// <summary>
        /// 高配通信周期 毫秒
        /// </summary>
        private int t_Interval_Fine = 2;//高配通信周期 毫秒
        /// <summary>
        /// 重连通信周期 毫秒
        /// </summary>
        private int t_Interval_ReConnect = 5000;//重连通信周期 毫秒
        /// <summary>
        /// 通信线程
        /// </summary>
        Thread thread = null;
        #endregion


        public ProtocolItem() 
        {
            #region 设定计时器

            OmegaTongXuntime();
            #endregion
        }
        public void Dispose()
        {
            this.thread.DisableComObjectEagerCleanup();
        }

        
        public void ChooseIniInterfaceType(object IniInterfaceType)
        {
            var type = IniInterfaceType.GetType().Name;
            switch (type)
            {
                case "ParameterTCP":
                    {
                        InterfaceType = new ModbusQi((JieKou.Modbus.ParameterTCP)IniInterfaceType);
                        InterfaceType.ReBackData += InterfaceType_ReBackData;
                    }
                    break;
                case "ParameterRTU":
                    {
                        //这里还没做
                        throw new NotImplementedException("IniInterfaceType(string type) RTU 这里还没做");
                    }
                    break;
                default:
                    break;
            }
        }

        private void InterfaceType_ReBackData(object data)
        {
            if (data is DataItem)
            {
                var item = (DataItem)data;

                //看看推送回来的数据是不是跟我的数据相符，如果相符，就拿来吧你。
                foreach (var testItem in dataItems)
                {
                    if (testItem.ParentName == item.ParentName &&
                        testItem.Description.StartAddress == item.Description.StartAddress &&
                        testItem.Description.Type == item.Description.Type &&
                        testItem.Description.BitIndex == item.Description.BitIndex &&
                        testItem.Description.UnitIdentifier == item.Description.UnitIdentifier &&
                        testItem.Description.Multiple == item.Description.Multiple &&
                        testItem.Description.Offset == item.Description.Offset &&
                        testItem.Description.RegisterOrder == item.Description.RegisterOrder &&
                        testItem.Description.SettingTimer == item.Description.SettingTimer)
                    {
                        //找到自己要去的地方了，赋值即可。
                        item.Description.LastReceivedBytes = testItem.Description.NewReceivedBytes;
                        item.Description.NewReceivedBytes = testItem.Description.NewReceivedBytes;
                        item.Description.LastReceivedDateTime = testItem.Description.LastReceivedDateTime;
                        item.Description.NewReceivedDateTime = testItem.Description.NewReceivedDateTime;                        
                        break;
                    }
                }

                

            }
        }

        

        public void Run()
        {
            InterfaceType?.Run();
        }

        public void Stop()
        {
            InterfaceType?.Stop();
        }

        public void AddDataItem(DataItem dataItem)
        {
            if (dataItems == null)
            {
                dataItems = new List<DataItem>();
            }
            dataItems.Add(dataItem);
        }





        #region 线程部分
        /// <summary>
        /// 开线程
        /// </summary>
        private void OmegaTongXuntime()
        {
            thread = new Thread(new ThreadStart(OmegaTongXunThread));
            thread.IsBackground = true;//后台执行线程
            thread.Start();//开始线程
        }
        /// <summary>
        /// 线程内容
        /// </summary>
        private void OmegaTongXunThread()
        {
            millisecond_Thread = t_Interval_Fine;//倒计一分钟
            while (millisecond_Thread >= 0)
            {
                millisecond_Thread--;
                if (millisecond_Thread == 0)
                {
                    millisecond_Thread--;
                    //计时完成后推出应用程序

                    JiShiQiWork();
                    millisecond_Thread = t_Interval_Fine;
                }
                Thread.Sleep(1);
            }

        }
        void JiShiQiWork()
        {
            if (dataItems != null)
            {
                for (int i = 0; i < dataItems.Count; i++)
                {
                    var item = dataItems[i];
                    TimeSpan ts = DateTime.Now - item.Description.NewReceivedDateTime ;
                    if (item.Description.NewReceivedDateTime == null || item.Description.LastReceivedDateTime == null)
                    {
                        //初次来，还没有记录时间，让他过去，自己去拿。
                        InterfaceType.PushReadData(item);
                    }
                    else if (ts.TotalMilliseconds > item.Description.SettingTimer)
                    {
                        //已经超时了，还不赶紧过去拿?快去！
                        InterfaceType.PushReadData(item);
                    }
                    else
                    {
                        //未超时，不用管。让他们再等一会。
                    }


                }
            }
            
        }

        #endregion
        

        
    }
}
